import json
import os


def load_records(path):
    """读取并返回历史账本"""
    try:
        with open(path, 'r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        return {}


def save_records(path, data):
    """写回最新账本"""
    with open(path, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)


def input_records():
    """循环收集本次用户输入"""
    records = {}
    category_map = {
        'food': '餐饮',
        'stat': '文具',
        'trans': '交通',
        'fun': '娱乐',
        'other': '其他'
    }

    while True:
        category = input("请输入消费类别（food/stat/trans/fun/other 或 中文名称），输入 q 结束：").strip().lower()
        if category == 'q':
            break

        if category in category_map.values():
            category = [k for k, v in category_map.items() if v == category][0]
        elif category in category_map:
            pass
        else:
            print("输入的消费类别无效，请重新输入。")
            continue

        while True:
            try:
                amount = float(input(f"请输入{category_map[category]}的金额："))
                break
            except ValueError:
                print("输入的金额无效，请输入一个正浮点数。")

        if category in records:
            records[category] = records[category] + amount
        else:
            records[category] = amount

    return records


def main():
    base_dir = 'D:/py'
    path = os.path.join(base_dir, '我的校园消费记录.txt')
    records = load_records(path)
    new_records = input_records()

    records.update(new_records)
    save_records(path, records)

    total_amount = sum(records.values())
    max_category = max(records, key=records.get)

    print("\n各类别当前累计消费金额：")
    for category, amount in records.items():
        print(f"{category_map[category]}: {amount:.2f}元")

    print(f"\n总消费金额：{total_amount:.2f}元")
    print(f"消费金额最高的类别：{category_map[max_category]} ({records[max_category]:.2f}元)")


if __name__ == "__main__":
    main()